package com.txsj.scan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lvfq.pickerview.TimePickerView;
import com.lvfq.pickerview.view.WheelTime;
import com.txsj.scan.R;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.InventoryBatchBean;
import com.txsj.scan.bean.NewBatchBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.presenter.AddBatchPresenter;
import com.txsj.scan.utils.AppDateMgr;
import com.txsj.scan.utils.DateYearUtils;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.ToastUtils;
import com.txsj.scan.view.AddBatchIView;
import com.txsj.scan.widget.popup.PopupOverdue;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by wangchuangjun on 2018/11/21
 * Desc: 录入批次盘点
 */

public class AddBatchActivity extends BaseActivity<AddBatchPresenter> implements AddBatchIView {

    private EditText et_inventory_count,et_validity_date;
    private TextView tv_expired_date,tv_birth_date,tv_vailidity_unit,tv_start;
    private RelativeLayout rel_root;
    private long subDay, subMonth, subYear, lastsubDay, lastsubYear, lastsubMonth;
    private String subDate;
    private String lastsubDate;

    int unitType = 1; //保质期单位类型
    private GoodsInfo goodsInfo;//商品实体
    private InventoryBatchBean inventoryBatchBean;//提交完成后返回的批次数据
    private WarehouseBean warehouseBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_batch);
        initView();
        initData();
    }

    private void initData() {
        if (null == getIntent() && TextUtils.isEmpty(getIntent().getStringExtra("data")))return;
        String json = getIntent().getStringExtra("data");
        goodsInfo = new Gson().fromJson(json,GoodsInfo.class);
        String warehouseJson = getIntent().getStringExtra("warehouse");
        warehouseBean = new Gson().fromJson(warehouseJson,WarehouseBean.class);
        tv_expired_date.setText(getResources().getText(R.string.long_validity));
    }

    private void initView() {
        et_inventory_count = (EditText) findViewById(R.id.et_inventory_count);
        et_validity_date = (EditText) findViewById(R.id.et_validity_date);
        tv_expired_date = (TextView) findViewById(R.id.tv_expired_date);
        tv_birth_date = (TextView) findViewById(R.id.tv_birth_date);
        tv_start = (TextView) findViewById(R.id.tv_start);
        tv_vailidity_unit = (TextView) findViewById(R.id.tv_vailidity_unit);
        rel_root = (RelativeLayout) findViewById(R.id.rel_root);

        et_validity_date.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    //输入逻辑处理
                    ClickAble();
                }
            }
        });

        tv_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toCommit();
            }
        });
    }

    private void toCommit() {
        if (TextUtils.isEmpty(et_inventory_count.getText().toString()) || Long.valueOf(et_inventory_count.getText().toString()) <= 0) {
            ToastUtils.showToast("请输入数量");
        } else {

            NewBatchBean batchBean = new NewBatchBean();
            //必传字段
            batchBean.setGs1_num(goodsInfo.getGs1_num());
            batchBean.setBrand_id(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
            if (TextUtils.isEmpty(tv_expired_date.getText().toString())
                    || getResources().getString(R.string.long_validity).equals(tv_expired_date.getText().toString())) {
                batchBean.setExpiry_time("9999-12-31");
            }else {
                batchBean.setExpiry_time(tv_expired_date.getText().toString().trim());
            }

            //可传空字段
            if (!TextUtils.isEmpty(tv_birth_date.getText().toString().trim())) {
                batchBean.setCreation_time(tv_birth_date.getText().toString().trim());
            }
            batchBean.setLife_unit(unitType);//默认是1暂时不管
            if (!TextUtils.isEmpty(et_validity_date.getText().toString().trim())) {
                batchBean.setShelf_life(Integer.valueOf(et_validity_date.getText().toString().trim()));
            }

            //提交的过程中不需要将盘点数量提交，只需在提交返回的信息中添加即可
            presenter.commitBatch(batchBean,warehouseBean.getWarehouse_id()+"");
        }
    }

    private void ClickAble() {
        //用來計算 過期時間
        if (!TextUtils.isEmpty(tv_birth_date.getText().toString())
                && !TextUtils.isEmpty(tv_vailidity_unit.getText().toString())) {
            lastTime();
        } else {
            makeTime();
        }
    }

    @Override
    protected AddBatchPresenter providePresenter() {
        return presenter = new AddBatchPresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    /**
     * 过期日期点击事件
     * @param view
     */
    public void clickExpiredDate(View view){
        selectDate(false,tv_expired_date);
    }

    /**
     * 生产日期点击事件
     * @param view
     */
    public void clickBirthDate(View view){
        selectDate(true,tv_birth_date);
    }

    /**
     * 开始添加
     * @param view
     */
    public void clickStart(View view) {

    }

    /**
     * 取消关闭界面
     * @param view
     */
    public void clickCancel(View view) {
        finish();
    }

    /**
     * 保质期单位
     * @param view
     */
    public void clickVilidity(View view){
        /**
         * 如果生产日期  保质期  不等于空  去计算  过期时间  等于空 计算 生产时间
         *  保质期选了之后才能进行动态变化
         */
        new PopupOverdue(getApplicationContext(), rel_root).builder().setFirseClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_vailidity_unit.setText("年");
                unitType = 3;
                if (!TextUtils.isEmpty(tv_birth_date.getText().toString()) &&
                        !TextUtils.isEmpty(et_validity_date.getText().toString())) {
                    //过期时间
                    lastTime();
                } else {
                    makeTime();
                }
            }
        }).setSecondClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unitType = 2;
                tv_vailidity_unit.setText("月");
                if (!TextUtils.isEmpty(tv_birth_date.getText().toString()) &&
                        !TextUtils.isEmpty(et_validity_date.getText().toString())) {
                    //过期时间
                    lastTime();
                } else {
                    makeTime();
                }
            }
        }).setThreadClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unitType = 1;
                tv_vailidity_unit.setText("天");
                if (!TextUtils.isEmpty(tv_birth_date.getText().toString()) &&
                        !TextUtils.isEmpty(et_validity_date.getText().toString())) {
                    //过期时间
                    lastTime();
                } else {
                    makeTime();
                }
            }
        }).show();
    }

    /**
     * 计算生产时间
     */
    private void makeTime() {
        if (TextUtils.equals(tv_vailidity_unit.getText().toString(), "年")) {
            if (lastsubYear > 0 && lastsubMonth > 0 && lastsubDay > 0)
                if (!TextUtils.isEmpty(et_validity_date.getText().toString())){
                    String makeTimes= (DateYearUtils.LastYear(lastsubYear, Long.parseLong(et_validity_date.getText().toString())) + "-" + lastsubMonth + "-" + lastsubDay).substring(0,4);
                    if (isLeapYear(Integer.valueOf(makeTimes))) {
                        //闰年
                        if (lastsubMonth == 2) {
                            //2月 29天
                            if (lastsubDay >= 29) {
                                lastsubDay = 29;
                            } else {
                                lastsubDay = 28;
                            }
                        }
                    }else {
                        if (lastsubDay >= 28)
                            lastsubDay = 28;
                    }
                    tv_birth_date.setText(DateYearUtils.LastYear(lastsubYear, Long.parseLong(et_validity_date.getText().toString())) + "-" + lastsubMonth + "-" + lastsubDay);
                }
        } else if (TextUtils.equals(tv_vailidity_unit.getText().toString(), "月")) {
            if (lastsubYear > 0 && lastsubMonth > 0 && lastsubDay > 0)
                if (!TextUtils.isEmpty(et_validity_date.getText().toString())) {
                    String makeTimes = (DateYearUtils.dateFormat(lastsubDate, Long.parseLong(et_validity_date.getText().toString())) + "-" + lastsubDay).substring(0,4);
                    if (isLeapYear(Integer.valueOf(makeTimes)) ){
                        //闰年
                        if (lastsubMonth == 2) {
                            //2月 29天
                            if (lastsubDay >= 29) {
                                lastsubDay = 29;
                            } else {
                                lastsubDay = 28;
                            }
                        }
                    } else {
                        if (lastsubDay >= 28)
                            lastsubDay = 28;
                    }

                    tv_birth_date.setText(DateYearUtils.dateFormat(lastsubDate, Long.parseLong(et_validity_date.getText().toString())) + "-" + lastsubDay);
                }
        } else if (TextUtils.equals(tv_vailidity_unit.getText().toString(), "天")) {
            if (lastsubYear > 0 && lastsubMonth > 0 && lastsubDay > 0)
                if (!TextUtils.isEmpty(et_validity_date.getText().toString())) {
                    String makeTimes = (DateYearUtils.getLastDateStr(lastsubDate, Integer.valueOf(et_validity_date.getText().toString()))).substring(0,4);
                    if (isLeapYear(Integer.valueOf(makeTimes))) {
                        //闰年
                        if (lastsubMonth == 2) {
                            //2月 29天
                            if (lastsubDay >= 29) {
                                lastsubDay = 29;
                            } else {
                                lastsubDay = 28;
                            }
                        }
                    } else {
                        if (lastsubDay >= 28)
                            lastsubDay = 28;
                    }
                    tv_birth_date.setText(DateYearUtils.getLastDateStr(lastsubDate, Integer.valueOf(et_validity_date.getText().toString())));
                }
        }
    }

    // 判断是否为闰年
    public static boolean isLeapYear(int year) {
        if (year % 100 == 0 && year % 400 == 0) {
            return true;
        } else if (year % 100 != 0 && year % 4 == 0) {
            return true;
        }
        return false;
    }


    /**
     * 重置过期时间
     */
    private void lastTime() {
        if (TextUtils.equals(tv_vailidity_unit.getText().toString(), "年")) {
            if (subYear > 0 && subMonth > 0 && subDay > 0)
                tv_expired_date.setText(DateYearUtils.dataYear(subYear,
                        Long.parseLong(et_validity_date.getText().toString())) + "-" + subMonth + "-" + subDay);
        } else if (TextUtils.equals(tv_vailidity_unit.getText().toString(), "月")) {
            if (subYear > 0 && subMonth > 0 && subDay > 0)
                tv_expired_date.setText(DateYearUtils.dearMonth(subYear,
                        subMonth, Long.parseLong(et_validity_date.getText().toString())) + "-" + subDay);
        } else if (TextUtils.equals(tv_vailidity_unit.getText().toString(), "天")) {
            if (!TextUtils.isEmpty(subDate))
                tv_expired_date.setText(DateYearUtils.getDateStr(subDate,
                        Long.parseLong(et_validity_date.getText().toString())));
        }
    }

    /**
     * 日期选择窗口
     */
    TimePickerView pvTime;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    private void selectDate(final boolean isStartDate, final TextView textView) {
        pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, WheelTime wheelTime) {
                try {
                    if (!isStartDate) {
                        //设置商品过期日期
                        if (AppDateMgr.isBeforeDate(format.format(date), format.format(new Date()))) {
                            ToastUtils.t(AddBatchActivity.this, "过期时间不能早于当前时间");
                        } else {
                            textView.setText(format.format(date));
                            if (!TextUtils.isEmpty(et_validity_date.getText().toString())) {
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(date);
                                lastsubYear = calendar.get(Calendar.YEAR);
                                lastsubMonth = subMonth = calendar.get(Calendar.MONTH) + 1;
                                lastsubDate = format.format(date);
                                lastsubDay = calendar.get(Calendar.DATE);
                                makeTime();
                            }
                        }
                    } else {
                        //设置商品生产日期
                        if (AppDateMgr.isBeforeDate(format.format(date), format.format(new Date()))) {
                            textView.setText(format.format(date));
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            subYear = calendar.get(Calendar.YEAR);
                            subMonth = calendar.get(Calendar.MONTH) + 1;
                            subDate = format.format(date);
                            subDay = calendar.get(Calendar.DATE);
                            if (!TextUtils.isEmpty(et_validity_date.getText().toString())) {
                                //重置过期日期
                                lastTime();
                            }
                        } else {
                            ToastUtils.t(AddBatchActivity.this, "生产日期不能晚于当前时间");
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
        pvTime.setCyclic(false);
        pvTime.setTextSize(14);
        pvTime.setTitle("请选择时间");
        pvTime.show();
    }

    @Override
    public void onError(String msg) {
        hideLoading();
        t(msg);
    }

    @Override
    public void onSuccess(InventoryBatchBean bean) {
        hideLoading();
        t("添加成功");
        inventoryBatchBean = bean;
        //将本地的盘点数量设置到实体当中
        inventoryBatchBean.setChange_num(Integer.valueOf(et_inventory_count.getText().toString()));
        Intent intent = getIntent();
        intent.putExtra("data",inventoryBatchBean);
        setResult(InventoryBatchActivity.REQUEST_ADD_BATC_CODE,intent);
        finish();
    }

    @Override
    public void onLoading() {
        showLoading();
    }
}
